<?php
// 开启错误提示，方便调试，生产环境建议关闭
ini_set('display_errors', 1);
error_reporting(E_ALL);

session_start();
// 检查Session是否能正常工作
if (!isset($_SESSION['session_test_write'])) {
    $_SESSION['session_test_write'] = true;
    if (empty($_SESSION['session_test_write'])) {
         header('Content-Type: application/json');
         echo json_encode([
            'success' => false, 
            'message' => '服务器Session功能异常，请检查服务器配置（例如session保存目录权限）。',
            'like_count' => 0
        ]);
        exit;
    }
}

require_once '../core/PluginModel.php';

header('Content-Type: application/json');
$response = ['success' => false, 'message' => '未知错误', 'like_count' => 0];

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    $response['message'] = '无效的请求方式';
    echo json_encode($response);
    exit;
}

$name = $_POST['name'] ?? '';
if (empty($name)) {
    $response['message'] = '缺少必要的参数';
    echo json_encode($response);
    exit;
}

if (isset($_SESSION['liked_plugins']) && is_array($_SESSION['liked_plugins']) && in_array($name, $_SESSION['liked_plugins'])) {
    $response['message'] = '您已经点过赞了';
    // 即使已点赞，也返回当前的点赞数
    try {
        $pluginModel = new PluginModel();
        $pluginData = $pluginModel->getPluginByName($name);
        $response['like_count'] = $pluginData['like_count'] ?? 0;
    } catch (Exception $e) {
        // do nothing
    }
    echo json_encode($response);
    exit;
}

try {
    $pluginModel = new PluginModel();
    $newLikeCount = $pluginModel->incrementLikeCount($name);

    if ($newLikeCount !== false) {
        if (!isset($_SESSION['liked_plugins']) || !is_array($_SESSION['liked_plugins'])) {
            $_SESSION['liked_plugins'] = [];
        }
        $_SESSION['liked_plugins'][] = $name;
        $response['success'] = true;
        $response['message'] = '点赞成功';
        $response['like_count'] = $newLikeCount;
    } else {
        // 增强的错误诊断
        $pluginData = $pluginModel->getPluginByName($name);
        if ($pluginData) {
            $response['message'] = '点赞失败：数据库中存在该插件，但更新操作失败。请检查数据库用户权限或列定义。插件名: ' . $name;
        } else {
            $response['message'] = '点赞失败：数据库中确实未找到该插件。插件名: ' . $name;
        }
    }
} catch (Exception $e) {
    $response['message'] = '操作失败: ' . $e->getMessage();
}

echo json_encode($response); 